<!-- src/components/CoursesManagement.vue -->
<template>
  <div class="courses-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-actions">
        <div class="search-filter">
          <div class="search-box">
            <input
              v-model="searchForm.title"
              type="text"
              placeholder="搜索课程名称"
              @input="debounceSearch"
              class="search-input"
            />
            <i class="icon-search"></i>
          </div>
          
          <select v-model="searchForm.category" @change="handleSearch" class="filter-select">
            <option value="">全部分类</option>
            <option value="1">农业种植</option>
            <option value="2">养殖技术</option>
            <option value="3">农产品加工</option>
            <option value="4">农村电商</option>
            <option value="5">农机操作</option>
          </select>
          
          <select v-model="searchForm.is_online" @change="handleSearch" class="filter-select">
            <option value="">全部模式</option>
            <option value="true">在线课程</option>
            <option value="false">线下课程</option>
          </select>
          
          <select v-model="searchForm.is_premium" @change="handleSearch" class="filter-select">
            <option value="">全部类型</option>
            <option value="true">精品课程</option>
            <option value="false">普通课程</option>
          </select>
          
          <button @click="resetFilters" class="btn btn-secondary">重置</button>
        </div>
        
        <button @click="showCreateModal = true" class="btn btn-primary">
          <i class="icon-plus"></i>新增课程
        </button>
      </div>
    </div>

    <!-- 课程统计卡片 -->
    <div class="stats-cards">
      <div class="stat-card">
        <div class="stat-icon">
          <i class="icon-book"></i>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ statistics.total || 0 }}</div>
          <div class="stat-label">总课程数</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon premium">
          <i class="icon-star"></i>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ statistics.premium || 0 }}</div>
          <div class="stat-label">精品课程</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon online">
          <i class="icon-monitor"></i>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ statistics.online || 0 }}</div>
          <div class="stat-label">在线课程</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon enrollment">
          <i class="icon-users"></i>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ statistics.totalEnrollment || 0 }}</div>
          <div class="stat-label">总报名数</div>
        </div>
      </div>
    </div>

    <!-- 课程表格 -->
    <div class="table-container">
      <div class="table-header">
        <h3>课程列表</h3>
        <div class="table-actions">
          <button @click="exportCourses" class="btn btn-outline">
            <i class="icon-download"></i>导出
          </button>
        </div>
      </div>
      
      <div class="table-wrapper" v-loading="loading">
        <table class="data-table">
          <thead>
            <tr>
              <th>课程名称</th>
              <th>分类</th>
              <th>教师</th>
              <th>模式</th>
              <th>视频云资源ID</th>
              <th>报名人数</th>
              <!-- <th>课时</th> -->
              <!-- <th>价格</th> -->
              <!-- <th>状态</th> -->
              <th>开课时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="course in courses" :key="course.id">
              <td>
                <div class="course-info">
                  <!-- <img :src="course.cover_image || '/default-course.png'" alt="封面" class="course-cover" /> -->
                  <div class="course-details">
                    <span class="course-title">{{ course.title }}</span>
                    <div class="course-tags">
                      <span v-if="course.is_premium" class="tag premium">精品</span>
                      <span v-if="course.enable_checkin" class="tag checkin">签到</span>
                    </div>
                  </div>
                </div>
              </td>
              <td>
                
                  {{ course.category.name}}
                
              </td>
              <td>{{ course.teacher.name || '-' }}</td>
              <td>
                <span class="mode-badge" :class="{ online: course.is_online }">
                  {{ course.is_online ? '在线' : '线下' }}
                </span>
              </td>
              <td>{{ course.video_resource || '-' }}</td>
              <td>
                <div class="enrollment-info">
                  <span class="enrollment-count">{{ course.enrollment_count || 0 }}</span>
                  <span class="enrollment-limit">/ {{ course.max_enrollment || '∞' }}</span>
                </div>
              </td>
              <!-- <td>{{ course.duration || 0 }}h</td> -->
              <!-- <td>
                <span class="price">
                  {{ course.price ? `¥${course.price}` : '免费' }}
                </span>
              </td> -->
              <!-- <td>
                <span class="status-badge" :class="getStatusClass(course)">
                  {{ getStatusText(course) }}
                </span>
              </td> -->
              <td>{{ formatDate(course.schedule) }}</td>
              <td>
                <div class="action-buttons">
                  <button @click="viewCourse(course)" class="btn-icon" title="查看">
                    <i class="icon-eye"></i>
                  </button>
                  <button @click="editCourse(course)" class="btn-icon" title="编辑">
                    <i class="icon-edit"></i>
                  </button>
                  <!-- <button @click="viewSubCourses(course)" class="btn-icon sub" title="子课程">
                    <i class="icon-layers"></i>
                  </button> -->
                  <!-- <button @click="manageCourse(course)" class="btn-icon manage" title="管理">
                    <i class="icon-settings"></i>
                  </button> -->
                  <button @click="deleteCourse(course)" class="btn-icon danger" title="删除">
                    <i class="icon-trash"></i>
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      
      <!-- 分页 -->
      <div class="pagination-wrapper">
        <div class="pagination-info">
          共 {{ total }} 条记录，第 {{ currentPage }}/{{ totalPages }} 页
        </div>
        <div class="pagination">
          <button 
            @click="changePage(currentPage - 1)" 
            :disabled="currentPage === 1"
            class="pagination-btn"
          >
            上一页
          </button>
          <span class="pagination-pages">
            <button
              v-for="page in visiblePages"
              :key="page"
              @click="changePage(page)"
              :class="['pagination-btn', { active: page === currentPage }]"
            >
              {{ page }}
            </button>
          </span>
          <button 
            @click="changePage(currentPage + 1)" 
            :disabled="currentPage === totalPages"
            class="pagination-btn"
          >
            下一页
          </button>
        </div>
      </div>
    </div>

    <!-- 创建/编辑课程模态框 -->
    <div v-if="showCreateModal || showEditModal" class="modal-overlay" @click="closeModals">
      <div class="modal modal-large" @click.stop>
        <div class="modal-header">
          <h3>{{ showCreateModal ? '新增课程' : '编辑课程' }}</h3>
          <button @click="closeModals" class="modal-close">
            <i class="icon-x"></i>
          </button>
        </div>
        
        <div class="modal-body">
          <form @submit.prevent="saveCourse">
            <div class="form-grid">
              <div class="form-group">
                <label>课程名称 *</label>
                <input
                  v-model="courseForm.title"
                  type="text"
                  required
                  placeholder="请输入课程名称"
                />
              </div>
              
              <div class="form-group">
                <label>课程分类 </label>
                <select v-model.number="courseForm.category_id" required>
                  <option value="">请选择分类</option>
                  <option value="135">种植技术</option>
                  <option value="136">养殖技术</option>
                  <option value="137">农产品加工</option>
                  <option value="138">农业营销</option>
                  <option value="139">农场管理</option>
                  <option value="140">农村电商</option>
                </select>
              </div>
              
               <!-- 上课模式 -->
              <div class="form-group">
                <label>上课模式 *</label>
                <select v-model="courseForm.is_online" required @change="handleModeChange">
                  <option value="">请选择上课模式</option>
                  <option :value="true">线上课程</option>
                  <option :value="false">线下课程</option>
                </select>
              </div>
              
              <!-- 视频云资源ID (仅线上模式显示) -->
              <div class="form-group" v-if="courseForm.is_online === true">
                <label>视频云资源ID *</label>
                <input
                  v-model="courseForm.video_resource"
                  type="text"
                  :required="courseForm.is_online === true"
                  placeholder="请输入视频云资源ID"
                />
              </div>
              
              <!-- 开课时间 (仅线下模式显示) -->
              <div class="form-group" v-if="courseForm.is_online === false">
                <label>开课时间 *</label>
                <input
                  v-model="courseForm.schedule"
                  type="datetime-local"
                  :required="courseForm.is_online === false"
                />
              </div>

              <div class="form-group">
                <label>授课教师</label>
                <select v-model="courseForm.teacher_id">
                  <option value="">请选择教师</option>
                  <option v-for="teacher in teachers" :key="teacher.id" :value="teacher.id">
                    {{ teacher.name }}
                  </option>
                </select>
              </div>
              
              <!-- <div class="form-group">
                <label>培训机构</label>
                <input
                  v-model.number="courseForm.agent_id"
                  type="number"
                  placeholder="机构ID"
                />
              </div> -->
              
              <!-- <div class="form-group">
                <label>课程时长（小时）</label>
                <input
                  v-model.number="courseForm.duration"
                  type="number"
                  min="1"
                  placeholder="请输入课程时长"
                />
              </div> -->
              
              <div class="form-group">
                <label>最大报名人数</label>
                <input
                  v-model.number="courseForm.max_enrollment"
                  type="number"
                  min="1"
                  placeholder="0表示无限制"
                />
              </div>
              
              <!-- <div class="form-group">
                <label>课程价格</label>
                <input
                  v-model.number="courseForm.price"
                  type="number"
                  min="0"
                  step="0.01"
                  placeholder="0表示免费"
                />
              </div>
               -->
              <!-- <div class="form-group">
                <label>开课时间</label>
                <input
                  v-model="courseForm.schedule"
                  type="datetime-local"
                />
              </div> -->
              
              <!-- <div class="form-group">
                <label>结课时间</label>
                <input
                  v-model="courseForm.schedule_end"
                  type="datetime-local"
                />
              </div>
               -->
              <!-- <div class="form-group">
                <label>父课程</label>
                <select v-model="courseForm.parent_course">
                  <option value="">无父课程</option>
                  <option v-for="course in parentCourses" :key="course.id" :value="course.id">
                    {{ course.title }}
                  </option>
                </select>
              </div> -->
            </div>
            
            <div class="form-group full-width">
              <label>课程简介</label>
              <textarea
                v-model="courseForm.notes"
                rows="4"
                placeholder="请输入课程简介"
              ></textarea>
            </div>
            
            <!-- <div class="form-group full-width">
              <label>封面图片URL</label>
              <input
                v-model="courseForm.cover_image"
                type="url"
                placeholder="请输入封面图片URL"
              />
            </div> -->
            
            <div class="form-group full-width">
              <label>课程标签（用逗号分隔）</label>
              <input
                v-model="courseForm.tags"
                type="text"
                placeholder="例如：实用,热门,推荐"
              />
            </div>
            
            <div class="form-options">
              <label class="checkbox-label">
                <input type="checkbox" v-model="courseForm.is_online" />
                在线课程
              </label>
              <label class="checkbox-label">
                <input type="checkbox" v-model="courseForm.is_premium" />
                精品课程
              </label>
              <label class="checkbox-label">
                <input type="checkbox" v-model="courseForm.enable_checkin" />
                启用签到
              </label>
            </div>
            
            <div class="modal-footer">
              <button type="button" @click="closeModals" class="btn btn-secondary">取消</button>
              <button type="submit" class="btn btn-primary" :disabled="saving">
                {{ saving ? '保存中...' : '保存' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 课程详情模态框 -->
    <div v-if="showDetailModal" class="modal-overlay" @click="showDetailModal = false">
      <div class="modal modal-large" @click.stop>
        <div class="modal-header">
          <h3>课程详情</h3>
          <button @click="showDetailModal = false" class="modal-close">
            <i class="icon-x"></i>
          </button>
        </div>
        
        <div class="modal-body">
          <div class="course-detail" v-if="selectedCourse">
            <div class="detail-header">
              <!-- <img :src="selectedCourse.cover_image || '/default-course.png'" alt="封面" class="course-cover-large" /> -->
              <div class="basic-info">
                <h4>{{ selectedCourse.title }}</h4>
                <div class="course-meta">
                  <span class="category">{{ getCategoryName(selectedCourse.category.name) }}</span>
                  <span class="mode" :class="{ online: selectedCourse.is_online }">
                    {{ selectedCourse.is_online ? '在线课程' : '线下课程' }}
                  </span>
                  <span v-if="selectedCourse.is_premium" class="premium">精品课程</span>
                </div>
                <div class="course-stats">
                  <div class="stat">
                    <label>报名人数：</label>
                    <span>{{ selectedCourse.enrollment_count || 0 }}</span>
                  </div>
                  <!-- <div class="stat">
                    <label>课程时长：</label>
                    <span>{{ selectedCourse.duration || 0 }}小时</span>
                  </div> -->
                  <!-- <div class="stat">
                    <label>课程价格：</label>
                    <span>{{ selectedCourse.price ? `¥${selectedCourse.price}` : '免费' }}</span>
                  </div> -->
                </div>
              </div>
            </div>
            
            <div class="detail-content">
              <div class="detail-section">
                <h5>课程信息</h5>
                <div class="detail-grid">
                  <div class="detail-item">
                    <label>授课教师：</label>
                    <span>{{ selectedCourse.teacher.name || '-' }}</span>
                  </div>
                  <!-- <div class="detail-item">
                    <label>培训机构：</label>
                    <span>{{ selectedCourse.agent_id || '-' }}</span>
                  </div> -->
                  <!-- <div class="detail-item">
                    <label>开课时间：</label>
                    <span>{{ formatDateTime(selectedCourse.schedule) }}</span>
                  </div> -->
                  <!-- <div class="detail-item">
                    <label>结课时间：</label>
                    <span>{{ formatDateTime(selectedCourse.schedule_end) }}</span>
                  </div> -->
                
                  <div class="detail-item">
                    <label>创建时间：</label>
                    <span>{{ formatDateTime(selectedCourse.created_at) }}</span>
                  </div>
                  <div class="detail-item">
                    <label>更新时间：</label>
                    <span>{{ formatDateTime(selectedCourse.updated_at) }}</span>
                  </div>
                </div>
              </div>
              
              <div class="detail-section" v-if="selectedCourse.description">
                <h5>课程简介</h5>
                <div class="description-full">
                  {{ selectedCourse.description }}
                </div>
              </div>
              
              <div class="detail-section" v-if="selectedCourse.tags && selectedCourse.tags.length">
                <h5>课程标签</h5>
                <div class="tags-list">
                  <span v-for="tag in selectedCourse.tags" :key="tag" class="tag">
                    {{ tag }}
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 子课程模态框 -->
    <div v-if="showSubCoursesModal" class="modal-overlay" @click="showSubCoursesModal = false">
      <div class="modal modal-large" @click.stop>
        <div class="modal-header">
          <h3>{{ selectedCourse?.title }} 的子课程</h3>
          <button @click="showSubCoursesModal = false" class="modal-close">
            <i class="icon-x"></i>
          </button>
        </div>
        
        <div class="modal-body">
          <div class="sub-courses-list" v-loading="loadingSubCourses">
            <div v-if="subCourses.length === 0" class="empty-state">
              <i class="icon-layers"></i>
              <p>该课程暂无子课程</p>
            </div>
            <div v-else class="sub-course-grid">
              <div v-for="subCourse in subCourses" :key="subCourse.id" class="sub-course-card">
                <div class="sub-course-header">
                  <h5>{{ subCourse.title }}</h5>
                  <span class="sub-course-duration">{{ subCourse.duration || 0 }}h</span>
                </div>
                <div class="sub-course-info">
                  <p class="sub-course-description">
                    {{ truncateText(subCourse.description, 60) }}
                  </p>
                  <div class="sub-course-meta">
                    <span><i class="icon-users"></i> {{ subCourse.enrollment_count || 0 }} 人</span>
                    <span><i class="icon-calendar"></i> {{ formatDate(subCourse.schedule_start) }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { courseAPI, teacherAPI } from '@/services/api'

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const loadingSubCourses = ref(false)
const courses = ref([])
const teachers = ref([])
const parentCourses = ref([])
const subCourses = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 搜索表单
const searchForm = reactive({
  title: '',
  category: '',
  is_online: '',
  is_premium: '',
  teacher_id: '',
  agent_id: ''
})

// 模态框状态
const showCreateModal = ref(false)
const showEditModal = ref(false)
const showDetailModal = ref(false)
const showSubCoursesModal = ref(false)
const selectedCourse = ref(null)

// 课程表单
const courseForm = reactive({
  title: '',
  category_id: '',
  teacher_id: '',
  agent_id: 4,
  duration: null,
  max_enrollment: null,
  price: null,
  schedule: '',
  video_resource: '',
  parent_course: '',
  cover_image: '',
  tags: '',
  is_online:'',
  is_premium: false,
  enable_checkin: false,
  notes: ''
})

// 统计数据
const statistics = ref({
  total: 0,
  premium: 0,
  online: 0,
  totalEnrollment: 0
})

// 计算属性
const totalPages = computed(() => Math.ceil(total.value / pageSize.value))
const visiblePages = computed(() => {
  const pages = []
  const maxVisible = 5
  const start = Math.max(1, currentPage.value - Math.floor(maxVisible / 2))
  const end = Math.min(totalPages.value, start + maxVisible - 1)
  
  for (let i = start; i <= end; i++) {
    pages.push(i)
  }
  return pages
})

// 防抖搜索
let searchTimeout = null
const debounceSearch = () => {
  clearTimeout(searchTimeout)
  searchTimeout = setTimeout(() => {
    handleSearch()
  }, 500)
}

// 方法
const fetchCourses = async () => {
  loading.value = true
  try {
    const params = {
      skip: (currentPage.value - 1) * pageSize.value,
      limit: pageSize.value,
      ...searchForm
    }
    
    // 清除空值
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null) {
        delete params[key]
      }
    })
    
    const response = await courseAPI.getCourses(params)
    courses.value = response.items
    total.value = response.total
    
    // 更新统计
    updateStatistics()
  } catch (error) {
    console.error('获取课程列表失败:', error)
  } finally {
    loading.value = false
  }
}

const fetchTeachers = async () => {
  try {
    const response = await teacherAPI.getTeachers({ limit: 100 })
    teachers.value = response.items
  } catch (error) {
    console.error('获取教师列表失败:', error)
  }
}

const fetchParentCourses = async () => {
  try {
    const response = await courseAPI.getCourses({ limit: 100 })
    parentCourses.value = response.items
  } catch (error) {
    console.error('获取父课程列表失败:', error)
  }
}

const updateStatistics = () => {
  statistics.value = {
    total: total.value,
    premium: courses.value.filter(c => c.is_premium).length,
    online: courses.value.filter(c => c.is_online).length,
    totalEnrollment: courses.value.reduce((sum, course) => sum + (course.enrollment_count || 0), 0)
  }
}

const handleSearch = () => {
  currentPage.value = 1
  fetchCourses()
}

const resetFilters = () => {
  Object.assign(searchForm, {
    title: '',
    category: '',
    is_online: '',
    is_premium: '',
    teacher_id: '',
    agent_id: ''
  })
  handleSearch()
}

const changePage = (page) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
    fetchCourses()
  }
}

const viewCourse = async (course) => {
  try {
    const response = await courseAPI.getCourse(course.id)
    selectedCourse.value = response
    showDetailModal.value = true
  } catch (error) {
    console.error('获取课程详情失败:', error)
  }
}

const editCourse = (course) => {
  // 正确映射字段
  Object.assign(courseForm, {
    title: course.title,
    category_id: course.category?.id || course.category_id,
    is_online: course.is_online,
    video_resource: course.video_resource,
    schedule: course.schedule ? formatDateForInput(course.schedule) : '',
    teacher_id: course.teacher?.id || course.teacher_id,
    agent_id: course.agent?.id || course.agent_id,
    max_enrollment: course.max_enrollment,
    notes: course.notes,
    tags: Array.isArray(course.tags) ? course.tags.join(',') : '',
    is_premium: course.is_premium,
    enable_checkin: course.enable_checkin
  })
  selectedCourse.value = course
  showEditModal.value = true
}

// 添加日期格式化辅助函数
const formatDateForInput = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toISOString().slice(0, 16) // 格式: YYYY-MM-DDTHH:MM
}

// 在 saveCourse 方法中，修正字段映射
const saveCourse = async () => {
  saving.value = true
  try {
    // 构建符合后端期望的数据结构
    const formData = {
      title: courseForm.title,
      category_id: courseForm.category_id,
      is_online: courseForm.is_online,
      video_resource: courseForm.video_resource,
      schedule: courseForm.schedule ? new Date(courseForm.schedule).toISOString() : null,
      is_premium: courseForm.is_premium,
      enable_checkin: courseForm.enable_checkin,
      notes: courseForm.notes,
      tags: courseForm.tags ? courseForm.tags.split(',').map(tag => tag.trim()) : [],
      agent_id: courseForm.agent_id || 4, // 提供默认值或从其他地方获取
      teacher_id: courseForm.teacher_id
    }
    
    // 清理空值
    Object.keys(formData).forEach(key => {
      if (formData[key] === '' || formData[key] === null || formData[key] === undefined) {
        delete formData[key]
      }
    })
    
    if (showCreateModal.value) {
      await courseAPI.createCourse(formData)
    } else {
      await courseAPI.updateCourse(selectedCourse.value.id, formData)
    }
    
    closeModals()
    fetchCourses()
  } catch (error) {
    console.error('保存课程失败:', error)
    alert('保存失败，请检查表单数据')
  } finally {
    saving.value = false
  }
}

const deleteCourse = async (course) => {
  if (confirm(`确定要删除课程 ${course.title} 吗？`)) {
    try {
      await courseAPI.deleteCourse(course.id)
      fetchCourses()
    } catch (error) {
      console.error('删除课程失败:', error)
    }
  }
}

const viewSubCourses = async (course) => {
  selectedCourse.value = course
  loadingSubCourses.value = true
  showSubCoursesModal.value = true
  
  try {
    const response = await courseAPI.getSubCourses(course.id)
    subCourses.value = response
  } catch (error) {
    console.error('获取子课程失败:', error)
    subCourses.value = []
  } finally {
    loadingSubCourses.value = false
  }
}

const manageCourse = (course) => {
  // 课程管理功能
  console.log('管理课程:', course.title)
}

const closeModals = () => {
  showCreateModal.value = false
  showEditModal.value = false
  selectedCourse.value = null
  // 重置表单
  Object.assign(courseForm, {
    title: '',
    category: '',
    description: '',
    teacher_id: '',
    agent_id: null,
    duration: null,
    max_enrollment: null,
    price: null,
    schedule_start: '',
    schedule_end: '',
    parent_course: '',
    cover_image: '',
    tagsString: '',
    is_online: false,
    is_premium: false,
    enable_checkin: false
  })
}

const exportCourses = () => {
  console.log('导出课程数据')
}

const getCategoryName = (category) => {
  const categories = {
    1: '农业种植',
    2: '养殖技术',
    3: '农产品加工',
    4: '农村电商',
    5: '农机操作'
  }
  return categories[category] || '未知'
}

const getStatusClass = (course) => {
  const now = new Date()
  const start = new Date(course.schedule_start)
  const end = new Date(course.schedule_end)
  
  if (now < start) return 'upcoming'
  if (now > end) return 'completed'
  return 'ongoing'
}

const getStatusText = (course) => {
  const now = new Date()
  const start = new Date(course.schedule_start)
  const end = new Date(course.schedule_end)
  
  if (now < start) return '未开始'
  if (now > end) return '已结束'
  return '进行中'
}

const truncateText = (text, maxLength) => {
  if (!text) return '-'
  if (text.length <= maxLength) return text
  return text.substring(0, maxLength) + '...'
}

const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleDateString('zh-CN')
}

const formatDateTime = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  fetchCourses()
  fetchTeachers()
  fetchParentCourses()
})
</script>

<style scoped>
.courses-management {
  padding: 20px;
}

/* 继承之前组件的基础样式... */
.page-header {
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
}

.search-filter {
  display: flex;
  gap: 12px;
  align-items: center;
}

.search-box {
  position: relative;
}

.search-input {
  width: 300px;
  padding: 8px 36px 8px 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
}

.search-box .icon-search {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #666;
}

.filter-select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  background: white;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.stat-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  background: #4F46E5;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
}

.stat-icon.premium {
  background: #F59E0B;
}

.stat-icon.online {
  background: #10B981;
}

.stat-icon.enrollment {
  background: #EF4444;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #1F2937;
}

.stat-label {
  color: #6B7280;
  font-size: 14px;
}

.table-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.table-header {
  padding: 20px;
  border-bottom: 1px solid #E5E7EB;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-header h3 {
  margin: 0;
  color: #1F2937;
}

.table-wrapper {
  overflow-x: auto;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th,
.data-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #E5E7EB;
}

.data-table th {
  background: #F9FAFB;
  font-weight: 600;
  color: #374151;
}

.course-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.course-cover {
  width: 48px;
  height: 36px;
  border-radius: 4px;
  object-fit: cover;
  background: #F3F4F6;
}

.course-details {
  flex: 1;
}

.course-title {
  display: block;
  font-weight: 500;
  color: #1F2937;
  margin-bottom: 4px;
}

.course-tags {
  display: flex;
  gap: 4px;
}

.tag {
  padding: 2px 6px;
  border-radius: 10px;
  font-size: 10px;
  font-weight: 500;
}

.tag.premium {
  background: #FEF3C7;
  color: #92400E;
}

.tag.checkin {
  background: #D1FAE5;
  color: #065F46;
}

.category-tag {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  background: #F3F4F6;
  color: #6B7280;
}

.category-tag.category-1 {
  background: #DBEAFE;
  color: #1E40AF;
}

.category-tag.category-2 {
  background: #D1FAE5;
  color: #065F46;
}

.category-tag.category-3 {
  background: #FEF3C7;
  color: #92400E;
}

.category-tag.category-4 {
  background: #FCE7F3;
  color: #BE185D;
}

.category-tag.category-5 {
  background: #E0E7FF;
  color: #3730A3;
}

.mode-badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  background: #FEE2E2;
  color: #DC2626;
}

.mode-badge.online {
  background: #D1FAE5;
  color: #065F46;
}

.enrollment-info {
  display: flex;
  align-items: center;
  gap: 2px;
}

.enrollment-count {
  font-weight: 500;
  color: #1F2937;
}

.enrollment-limit {
  color: #6B7280;
  font-size: 12px;
}

.price {
  font-weight: 500;
  color: #EF4444;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.upcoming {
  background: #FEF3C7;
  color: #92400E;
}

.status-badge.ongoing {
  background: #D1FAE5;
  color: #065F46;
}

.status-badge.completed {
  background: #F3F4F6;
  color: #6B7280;
}

.action-buttons {
  display: flex;
  gap: 4px;
}

.btn-icon {
  width: 32px;
  height: 32px;
  border: none;
  border-radius: 4px;
  background: #F3F4F6;
  color: #6B7280;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.btn-icon:hover {
  background: #E5E7EB;
  color: #374151;
}

.btn-icon.sub {
  background: #E0E7FF;
  color: #3730A3;
}

.btn-icon.manage {
  background: #FEF3C7;
  color: #92400E;
}

.btn-icon.danger {
  background: #FEE2E2;
  color: #DC2626;
}

.pagination-wrapper {
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top: 1px solid #E5E7EB;
}

.pagination {
  display: flex;
  gap: 8px;
  align-items: center;
}

.pagination-btn {
  padding: 8px 12px;
  border: 1px solid #D1D5DB;
  background: white;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.pagination-btn:hover:not(:disabled) {
  background: #F3F4F6;
}

.pagination-btn.active {
  background: #4F46E5;
  color: white;
  border-color: #4F46E5;
}

.pagination-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-large {
  max-width: 900px;
}

.modal-header {
  padding: 20px;
  border-bottom: 1px solid #E5E7EB;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  color: #1F2937;
}

.modal-close {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #6B7280;
}

.modal-body {
  padding: 20px;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 16px;
  margin-bottom: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.form-group.full-width {
  grid-column: 1 / -1;
}

.form-group label {
  font-weight: 500;
  color: #374151;
  font-size: 14px;
}

.form-group input,
.form-group select,
.form-group textarea {
  padding: 8px 12px;
  border: 1px solid #D1D5DB;
  border-radius: 6px;
  font-size: 14px;
}

.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
  outline: none;
  border-color: #4F46E5;
  box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
}

.form-options {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  font-size: 14px;
  color: #374151;
}

.modal-footer {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  padding-top: 20px;
  border-top: 1px solid #E5E7EB;
}

.btn {
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  border: none;
}

.btn-primary {
  background: #4F46E5;
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background: #4338CA;
}

.btn-secondary {
  background: #F3F4F6;
  color: #374151;
  border: 1px solid #D1D5DB;
}

.btn-secondary:hover {
  background: #E5E7EB;
}

.btn-outline {
  background: white;
  color: #4F46E5;
  border: 1px solid #4F46E5;
}

.btn-outline:hover {
  background: #4F46E5;
  color: white;
}

/* 课程详情样式 */
.course-detail {
  max-width: 100%;
}

.detail-header {
  display: flex;
  gap: 20px;
  align-items: flex-start;
  margin-bottom: 24px;
  padding-bottom: 20px;
  border-bottom: 1px solid #E5E7EB;
}

.course-cover-large {
  width: 120px;
  height: 90px;
  border-radius: 8px;
  object-fit: cover;
  background: #F3F4F6;
}

.basic-info h4 {
  margin: 0 0 12px 0;
  color: #1F2937;
  font-size: 20px;
}

.course-meta {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
  flex-wrap: wrap;
}

.course-meta > span {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.course-meta .category {
  background: #DBEAFE;
  color: #1E40AF;
}

.course-meta .mode {
  background: #FEE2E2;
  color: #DC2626;
}

.course-meta .mode.online {
  background: #D1FAE5;
  color: #065F46;
}

.course-meta .premium {
  background: #FEF3C7;
  color: #92400E;
}

.course-stats {
  display: flex;
  gap: 24px;
  flex-wrap: wrap;
}

.course-stats .stat {
  display: flex;
  gap: 4px;
  font-size: 14px;
}

.course-stats .stat label {
  color: #6B7280;
}

.course-stats .stat span {
  color: #1F2937;
  font-weight: 500;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section h5 {
  margin: 0 0 16px 0;
  color: #1F2937;
  font-size: 16px;
}

.detail-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.detail-item {
  display: flex;
  gap: 8px;
}

.detail-item label {
  font-weight: 500;
  color: #6B7280;
  min-width: 80px;
}

.description-full {
  line-height: 1.6;
  color: #374151;
  padding: 12px;
  background: #F9FAFB;
  border-radius: 6px;
}

.tags-list {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.tags-list .tag {
  padding: 4px 8px;
  background: #E0E7FF;
  color: #3730A3;
  border-radius: 12px;
  font-size: 12px;
}

/* 子课程样式 */
.sub-courses-list {
  min-height: 300px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #6B7280;
}

.empty-state i {
  font-size: 48px;
  margin-bottom: 16px;
}

.sub-course-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.sub-course-card {
  background: white;
  border: 1px solid #E5E7EB;
  border-radius: 8px;
  padding: 16px;
  transition: all 0.2s;
}

.sub-course-card:hover {
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.sub-course-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.sub-course-header h5 {
  margin: 0;
  color: #1F2937;
  font-size: 16px;
}

.sub-course-duration {
  padding: 2px 8px;
  background: #F3F4F6;
  color: #6B7280;
  border-radius: 12px;
  font-size: 12px;
}

.sub-course-description {
  color: #6B7280;
  font-size: 14px;
  line-height: 1.5;
  margin-bottom: 12px;
}

.sub-course-meta {
  display: flex;
  gap: 16px;
  font-size: 12px;
  color: #9CA3AF;
}

.sub-course-meta span {
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-actions {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-filter {
    flex-wrap: wrap;
  }
  
  .search-input {
    width: 100%;
  }
  
  .stats-cards {
    grid-template-columns: 1fr;
  }
  
  .form-grid {
    grid-template-columns: 1fr;
  }
  
  .form-options {
    flex-direction: column;
    gap: 8px;
  }
  
  .detail-header {
    flex-direction: column;
    text-align: center;
  }
  
  .detail-grid {
    grid-template-columns: 1fr;
  }
  
  .course-stats {
    justify-content: center;
  }
  
  .sub-course-grid {
    grid-template-columns: 1fr;
  }
}
</style>